import { ipcMain } from 'electron'
import { CommonWindow } from './CommonWindow'
import { configTypes } from '@globalTypes/global'
import { mainWinEntity } from './mainWindow'
import { StorageTool } from '../composables/StorageTool'
import { clockIcon } from '../composables/icon'
import { setAutoOpenStatus } from '../composables/autoOpenStatus'

export let settingWinEntity: CommonWindow | null

export function settingWindow() {
  if (settingWinEntity) {
    if (settingWinEntity.getWindow().isMinimized()) {
      settingWinEntity.getWindow().restore()
    }
    settingWinEntity.getWindow().focus()
    return settingWinEntity
  }
  const settingWin = new CommonWindow(
    {
      width: 1000,
      height: 700,
      title: '设置',
      // alwaysOnTop: true, // 窗口置顶
      center: true, // 居中
      transparent: false, // 透明
      frame: true, // 边框
      autoHideMenuBar: true, // 自动隐藏菜单栏
      icon: clockIcon,
      minimizable: true, // 是否可以最小化
      maximizable: false, // 禁止最大化
      resizable: true // 窗口缩放
    },
    'setting',
    '/setting/timer_config'
  )

  settingWinEntity = settingWin
  settingWin.addWindowCloseListener(() => {
    settingWinEntity = null
  })
  settingWin.show()
  syncTimeConfigEventListener()
  syncTimeInformEventListener()
  return settingWin
}

function syncTimeConfigEventListener() {
  ipcMain.on('sync-time-config-store-setting', (_event, config: configTypes.Config) => {
    // 持久化
    const storageTool = new StorageTool('config')
    storageTool.setStorageStr('timer', JSON.stringify(config))
    // 发送事件到主窗口
    mainWinEntity?.getWindow().webContents.send('sync-time-config-store-main')
    setAutoOpenStatus(config.autoOpen)
  })
}

function syncTimeInformEventListener() {
  ipcMain.on('sync-time-inform-store-setting', (_event, informListStr: string) => {
    // 持久化
    const storageTool = new StorageTool('inform')
    storageTool.setStorageStr('timer', informListStr)
    // 发送事件到主窗口
    mainWinEntity?.getWindow().webContents.send('sync-time-inform-store-main')
  })
}

export function addOpenSettingWindowListener() {
  ipcMain.on('open-setting-window', () => {
    settingWindow()
  })
}
